package com.home.zcym.utils;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.dataformat.xml.XmlMapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.Map;

/**
 * 格式化工具类
 */
public class ReMapSerializer {

  private static final Logger LOGGER = LoggerFactory.getLogger(ReMapSerializer.class);

  private static ObjectMapper om = new ObjectMapper();
  private static ObjectMapper xm = new XmlMapper();

  public static String serialize(Map map, String format) {
    String ret = "serialize error";
    if (format.equalsIgnoreCase("xml")) {
      try {
        ret = xm.writeValueAsString(map);
        ret = ret.replace("<HashMap>", "").replace("</HashMap>", "");
      } catch (JsonProcessingException e) {
        LOGGER.error(e.getMessage(), e);
      }
    } else {
      try {
        ret = om.writeValueAsString(map);
      } catch (JsonProcessingException e) {
        LOGGER.error(e.getMessage(), e);
      }
    }

    return ret;
  }

  public static String serialize(Object object, String format) {
    String ret = "serialize error";
    if (format.equalsIgnoreCase("xml")) {
      try {
        ret = xm.writeValueAsString(object);
        if (object instanceof Map) {
          ret = ret.replace("<HashMap>", "").replace("</HashMap>", "");
        }
      } catch (JsonProcessingException e) {
        LOGGER.error(e.getMessage(), e);
      }
    } else {
      try {
        ret = om.writeValueAsString(object);
      } catch (JsonProcessingException e) {
        LOGGER.error(e.getMessage(), e);
      }
    }

    return ret;
  }

  public static String serialize(Object object) {
    String ret = "serialize error";
    try {
      ret = om.writeValueAsString(object);
    } catch (JsonProcessingException e) {
      LOGGER.error(e.getMessage(), e);
    }

    return ret;
  }
}
